package org.boot.wxipad.common.util.http.apache;

import org.apache.hc.client5.http.HttpResponseException;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.http.Consts;

import java.io.IOException;

/**
 * @author liyuncong
 * @version 1.0
 * @file Utf8ResponseHandler
 * @brief Utf8ResponseHandler
 * @details Utf8ResponseHandler
 * @date 2024-08-09
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-08-09               liyuncong          Created
 */
public class Utf8ResponseHandler implements HttpClientResponseHandler<String> {

    public static final HttpClientResponseHandler<String> INSTANCE = new Utf8ResponseHandler();

    @Override
    public String handleResponse(ClassicHttpResponse response) throws IOException, ParseException {
        int code = response.getCode();
        HttpEntity entity = response.getEntity();
        if (code >= 300) {
            EntityUtils.consume(entity);
            throw new HttpResponseException(code, response.getReasonPhrase());
        }
        return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
    }
}
